#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Datetime: 2022/11/1 10:17
# @Author  : CHENWang
# @Site    : 
# @File    : google_trends.py
# @Software: PyCharm

"""
脚本说明: https://pypi.org/project/pytrends/
"""

import pandas as pd
import plotly.express as px
from pytrends.request import TrendReq

pytrends = TrendReq(hl='en-US', tz=0, timeout=(10, 25), retries=2, backoff_factor=0.1)
# hl stands for hosting language for accessing Google Trends;
# tz stands for timezone, in this example, we use the US time zone (represented in minutes), which is 360.

# build payload
kw_list = ["cryptocurrency"]  # list of keywords to get data
pytrends.build_payload(kw_list, cat=0, timeframe='2016-01-01 2021-01-01', geo='', gprop='')
data = pytrends.interest_over_time()  # 默认返回的是周频数据
data1 = data.reset_index()

pytrends.build_payload(kw_list, cat=0, timeframe='today 5-y', geo='', gprop='')
data = pytrends.interest_over_time()  # 默认返回的是周频数据
data2 = data.reset_index()

data = data1.merge(data2, on='date', how='outer')
data['ratio'] = data['cryptocurrency_x'] / data['cryptocurrency_y']
if data['ratio'].max() == 1 and data['ratio'].min() == 1:
    data = pd.concat([data1, data2], axis=0)
    data.drop_duplicates(subset=['date'], keep='last', inplace=True)
    data.sort_values(by='date', inplace=True)
else:
    pass
fig = px.line(data, x="date", y=['cryptocurrency'], title='Keyword Web Search Interest Over Time')
fig.show()

# Historical Hourly Interest
# If you are interested in the hourly interest of the keyword, you can use the get_historical_intereset() method to fetch hourly data according to the time you have specified.
historical_interest = pytrends.get_historical_interest(kw_list, year_start=2021, month_start=9, day_start=1, hour_start=0,
                                 year_end=2021, month_end=9, day_end=30, hour_end=0, cat=0, sleep=0)
data = historical_interest.reset_index()
fig = px.line(data, x="date", y=['cryptocurrency'], title='Keyword Web Search Historical Hourly Interest')
fig.show()

# Interest by Region
# Sometimes you can be interested to know the performance of the keyword per region.
by_region = pytrends.interest_by_region(resolution='COUNTRY', inc_low_vol=True, inc_geo_code=False)
by_region.head(10)
# by region greater than 10 searches
by_region[by_region["cryptocurrency"] > 10]

# Related Queries
# Pytrends can also help you find keywords that are closely tied to a primary keyword of your choice and then return a list of related keywords shown on Google Trends.
# Let us find a list of related queries for “machine learning” and return the top queries.
data = pytrends.related_queries()
data['cryptocurrency']['top']

# Keyword Suggestion
# Google Trends can give you a list of keyword suggestions related to your primary keyword.
# In the example below, you will send a request to find suggestions for a keyword called "Business Intelligence."
keywords = pytrends.suggestions(keyword='cryptocurrency')
df = pd.DataFrame(keywords)
print(df)